// pages/my/my-statistics/index.js
const controllers = require('../../pages/controllers/controllerOrder').controller
const controllerIndex = require('../../pages/controllers/controllerIndex.js').controller;
import * as echarts from '../ec-canvas/echarts';
const app = getApp();
// echarts初始化
let chart

function initChart(canvas, width, height) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: 2 // 像素比
  });
  canvas.setChart(chart);
  return chart;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabList: ["提成结算记录", "提成提现记录"],
    currentIndex: 0,
    startTime: "",
    endTime: "",
    status: 0,
    accountId: '',
    orderList: [],
    shopAccountId: wx.getStorageSync('shopAccountId'),
    show: false,
    // ---
    total: {},
    settlement: '',
    list: [],
    upimg: 'https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/o2o/agent/table/on_line_icon_01%402x.png',
    dowmimg: 'https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/o2o/agent/table/offline_icon_01%402x.png',
    pageNumber: 1,
    pageSize: 20,
    lastPage: false,
    getMore: false,
    time: '',
    commission: 0,
    balance: 0,
    all: 0,
    upPrice: 0,
    lowPrice: 0,
    payPrice: 0,
    ec: {
      onInit: initChart
    }
  },

  onLoad: function (options) {
    this.staffDetail()
    this.getOrderList()
  },
  // 员工信息
  staffDetail() {
    controllerIndex.staffDetail({
      sessionId: wx.getStorageSync('token'),
      shopId: wx.getStorageSync('shopId'),
      shopAccountId: wx.getStorageSync('shopAccountId'),
    }).then(res => {
      this.handleUserInfo(res.data)
      // echarts初始化完成后赋值
      setTimeout(() => {
        this.initChartOption()
      }, 1000)
    })
  },
  handleUserInfo(data) {
    data.lowOrderMoney = data.lowOrderMoney ? data.lowOrderMoney.toFixed(2) : '00.00'
    data.upOrderMoney = data.upOrderMoney ? data.upOrderMoney.toFixed(2) : '00.00'
    data.totleWithdrawal = (data.waitMoney || 0) + (data.withdrawMoney || 0)
    data.totleWithdrawal = data.totleWithdrawal ? data.totleWithdrawal.toFixed(2) : '00.00'
    data.withdrawalMoney = data.withdrawalMoney ? data.withdrawalMoney.toFixed(2) : '00.00'
    data.waitMoney = data.waitMoney ? data.waitMoney.toFixed(2) : '00.00'
    this.setData({
      userInfo: data,
    })
  },
  initChartOption() {
    const value1 = this.data.userInfo.withdrawalMoney
    const value2 = this.data.userInfo.waitMoney
    chart.setOption({
      color: ["#F56666", "#66C1F5"],
      legend: {
        show: false,
      },
      series: [{
        type: 'pie',
        radius: ['54%', '84%'],
        center: ["50%", "38%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          formatter: '{d}%',
          position: "inside"
        },
        // startAngle:-5,
        data: [{
            value: value1 || 0,
            name: "已提现"
          }, {
            value: value2 || 0,
            name: "未提现"
          }

        ]
      }]
    })
  },

  //改变开始时间
  bindStartChange(e) {
    this.setData({
      startTime: e.detail.value
    })
    this.getOrderList()
  },

  //改变结束时间
  bindEndChange(e) {
    this.setData({
      endTime: e.detail.value
    })
    this.getOrderList()
  },
  // 重置时间
  reset() {
    this.setData({
      endTime: '',
      startTime: ''
    })
    this.getOrderList()
  },
  // 打开申请
  showDialog() {
    this.setData({
      show: true
    })
  },
  // 关闭弹窗
  closeDialog() {
    this.setData({
      show: false,
      money: ''
    })
    setTimeout(() => {
      this.initChartOption()
    }, 200)
  },
  // 全部提现
  applyAll() {
    this.setData({
      money: this.data.userInfo.waitMoney
    })
  },
  // 获取提现额
  inputMoney(e) {
    this.setData({
      money: e.detail.value
    })
  },
  // 申请提现
  apply() {
    controllers.shopStaffWithdraw({
      money: Number(this.data.money),
      sessionId: wx.getStorageSync('token'),
      shopId: wx.getStorageSync('shopId'),
      accountId: wx.getStorageSync('accountId'),
      shopAccountId: wx.getStorageSync('shopAccountId'),
    }).then(res => {
      this.closeDialog()
      this.staffDetail()
      wx.showToast({
        title: '申请提现成功',
      })
    })
  },

  // 切换栏目
  changeIndex(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      currentIndex: index
    })
    this.getOrderList()
  },
  // 获取订单列表
  getOrderList() {
    if (!this.data.getMore) {
      this.setData({
        orderList: [],
        pageNumber: 1
      })
    }
    let value = {
      sessionId: wx.getStorageSync('token'),
      shopId: wx.getStorageSync('shopId'),
      accountId: wx.getStorageSync('accountId'),
      shopAccountId: wx.getStorageSync('shopAccountId'),
      endTime: this.data.endTime,
      startTime: this.data.startTime,
      pageNumber: this.data.pageNumber,
      pageSize: 20,
    }
    let index = this.data.currentIndex
    if (index == 0) {
      //提成记录
      value.genre = 0,
      value.amountType = 0,
      controllerIndex.orderStaff(value).then((res) => {
        this.handleOrderData(res.data)
      })
    } else {
      // 提现记录
      controllerIndex.shopStaffPage(value).then((res) => {
        this.handleOrderData(res.data)
      })
    }

  },

  // 数据处理
  handleOrderData(data) {
    const index = this.data.currentIndex
    const list = data.list
    const orderList = this.data.orderList
    orderList.push(...list)
    this.setData({
      orderList,
      lastPage: data.lastPage,
      getMore: false
    })
    orderList.forEach(item => {
      if (index == 0) {
        item.stateName = '已结算'
        item.greenColor = true
        if (item.lowLine) {
          item.typeName = '线下订单收入'
        } else {
          if (item.type == 1) {
            item.typeName = '线上订单收入'
          } else if (item.type == 7) {
            item.typeName = '云服务订单收入'
          }
        }
      } else {
        switch (item.state) {
          case 0:
            item.stateName = '待处理'
            break
          case 1:
            item.stateName = '提现失败'
            break
          case 2:
            item.stateName = '提现成功'
            item.greenColor = true
            break
        }
      }

    })
    this.setData({
      orderList
    })
  },

  // 详情页
  toOrderDetails(e) {
    const index = e.currentTarget.dataset.index
    const currentIndex = this.data.currentIndex
    let item = this.data.orderList[index]
    if (currentIndex == 0) {
      if (item.lowLine) {
        wx.navigateTo({
          url: '/pages/settlement/OrderDetails/OrderDetails?orderNo=' + item.orderNo,
        })
      } else {
        if (item.type == 1) {
          wx.navigateTo({
            url: '/pages/order/productOrder-detail/productOrder-detail?id=' + item.orderNo + '&state=' + item.state
          })
        } else if (item.type == 7) {
          wx.navigateTo({
            url: '/pages/order/cloudOrder-detail/cloudOrder-detail?id=' + item.orderNo + '&state=' + item.state
          })
        }
      }
    } else {
      let detail = {
        userInfo: this.data.userInfo,
        orderDetail: item
      }
      detail = JSON.stringify(detail)
      wx.navigateTo({
        url: '/pages-echarts/PersonnelDetails/commissionDetail/commissionDetail?detail=' + detail
      })
    }

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.lastPage) return
    this.setData({
      pageNumber: this.data.pageNumber + 1,
      getMore: true
    })
    this.getOrderList()
  },

})